package server;

import java.io.*;
import java.net.*;
import java.util.*;

class Server {
	
	public static void main(String argv[]) throws Exception {
		Server serverInstance = new Server();
	}
	
	public static Map<String, Integer> socketMap;
	public static Socket[] sockets;
//	public static int numSocket = 0;
//	public static String[] serverList;
//	public static DataOutputStream[] out;
	static String localAddr;
//	public static Buffer[] buffers;
	
	public Server() {
		socketMap = new HashMap<String, Integer>();
		sockets = new Socket[10];
		int numSocket = 0;
		DataOutputStream[] out = new DataOutputStream[10];
		Buffer[] buffers = new Buffer[10];
		synchronized (sockets) {
			try {
				// Get IP Address
				localAddr = (InetAddress.getLocalHost()).getHostAddress();
			    System.out.println("server local IP address: " + localAddr);
				
	//		    localAddr = "192.168.56.110"; //pour tester
				
			    /*
			     * TODO: create connections to other servers
			     */
			    
				ServerSocket ss = new ServerSocket(1026);
				System.out.println("Listening on port 1026...");
				while (true) {	
					Socket connectionSocket = ss.accept();
					System.out.println("Socket created with " + connectionSocket.getInetAddress() + " index " + numSocket);
				    sockets[numSocket] = connectionSocket;
				    buffers[numSocket] = new Buffer();
				    out[numSocket] = new DataOutputStream(connectionSocket.getOutputStream());
				    socketMap.put((connectionSocket.getInetAddress()).getHostAddress(), numSocket);
				    SendThread st = new SendThread(connectionSocket , numSocket, buffers);
	//			    st.start();
				    ReceiveThread rt = new ReceiveThread(connectionSocket, out, buffers);
					rt.start();
	//				rt.join();
					numSocket++;		  
				}
			}
			  catch (Exception ex) {}
		}
	}			
	
	public static String getServerAddr(String localAdd){
		String[] x = localAdd.split("\\.");
		String server = "";
		server += x[0] + '.' + x[1] + '.' + x[2] + '.';
		int lastOctet = Integer.parseInt(x[3]);
		server += lastOctet - lastOctet%10;
		return server;
	}
	
	public static Socket getSocket(String add){
		int id = socketMap.get(add);
		return sockets[id];
	}
	
	public static int getSocketID(String add){
		return socketMap.get(add);
	}
}